<template>
	<el-dialog
	  v-model="dialog.visible"
	  :title="dialog.title"
	  destroy-on-close
	  :append-to-body="false"
	  width="550px"
	  class="editor-dialog-c"
	  @close="resetForm"
	  draggable
	  :close-on-click-modal="false"
	>
	
		<el-form
			ref="formRef"
			:model="formData"
			:rules="formRules"
			label-width="80px"
		>
			<el-form-item label="json数据" prop="content">
				<el-input v-model="formData.content" type="textarea" :rows="16" placeholder="请输入json数据" />
			</el-form-item>
		</el-form>
	
	<template #footer>
	  <div class="dialog-footer">
		<el-button color="#626aef" @click="submitForm"  :loading="loading">确 定</el-button>
		<el-button color="#1e1e1e" @click="() => closeDialog('', null)"  :loading="loading">取 消</el-button>
	  </div>
	</template>
	
	</el-dialog>
</template>

<script lang="ts" setup>
	import { ComponentLibraryService } from '@/api/visual/componentLibraryApi'
	import type {FormRules } from 'element-plus'
	
	const loading = ref(false);
	const dialog = ref({
		visible:false,
		title:'',
	});
	const formRef=ref();
	const formData=ref<any>({
		id:'',
		type: '',
		content:''
	})
	
	const formRules=reactive<FormRules>({
		content: [{ required: true, message: "请输入json数据", trigger: "blur" }],
	});
	

const defaultField = {
  fieldMapping: "",
  required: false,
  batchModify: false,
  readonly: false,
  isFieldValue: false,
  isDbField: false,
  isNotUpdateDbField: true,
  isOutField: false,
  isPrimaryKey: false,
  tableName: "",
  sourceId: "",
  source: false,
  isUuid: false,
  display: true,
  defaultValue: undefined
}

function getDataTypeAndSpecs(value: any) {
  if (typeof value === 'string') {
    return { type: 'string', specs: { length: Math.max(40, value.length) } }
  }
  if (typeof value === 'number') {
    return { type: 'string', specs: { length: 40 } } // 可自定义 int/float
  }
  if (typeof value === 'boolean') {
    return { type: 'boolean', specs: { isTrue: '是', isFalse: '否' } }
  }
  if (Array.isArray(value)) {
    return { type: 'array', specs: { type: 'text', count: value.length || 10 } }
  }
  if (typeof value === 'object' && value !== null) {
    return { type: 'struct', specs: [] }
  }
  return { type: 'string', specs: { length: 40 } }
}

function parseToFieldParams(data: any, key = '', name = ''): any[] {
  if (Array.isArray(data)) {
    // 数组：只生成一个参数项，类型为 array
    const { type, specs } = getDataTypeAndSpecs(data)
    return [{
      ...defaultField,
      name: name || key,
      identifier: key,
      dataType: { type, specs },
      defaultValue: undefined,
      display: true
    }]
  } else if (typeof data === 'object' && data !== null) {
    // 对象：每个 key 递归
    return Object.entries(data).map(([k, v]) => {
      const { type, specs } = getDataTypeAndSpecs(v)
      let param: any = {
        ...defaultField,
        name: k,
        identifier: k,
        dataType: { type, specs },
        defaultValue: (type === 'string' || type === 'boolean' || type === 'number') ? v : undefined,
        display: true
      }
      if (type === 'struct') {
        param.dataType.specs = parseToFieldParams(v)
      }
      return param
    })
  } else {
    // 基础类型
    const { type, specs } = getDataTypeAndSpecs(data)
    return [{
      ...defaultField,
      name: key,
      identifier: key,
      dataType: { type, specs },
      defaultValue: data,
      display: true
    }]
  }
}
	async function openDialog(row?: any, type?: string) {
		if('Input'==type){
			dialog.value.visible=true;
			dialog.value.title='输入参数';
			formData.value.id = row.id;
			formData.value.type = type;
		}else{
			dialog.value.visible=true;
			dialog.value.title='输出参数';
			formData.value.id = row.id;
			formData.value.type = type;
		}
	}
	
	const submitForm = () => {
  formRef.value.validate((isValid: boolean) => {
    if (isValid) {
      try {
        const parsed = JSON.parse(formData.value.content)
        let result = []
        if (Array.isArray(parsed)) {
          result = parsed.map((item, idx) => parseToFieldParams(item, String(idx))).flat()
        } else if (typeof parsed === 'object' && parsed !== null) {
          result = parseToFieldParams(parsed)
        } else {
          ElMessage.error('JSON格式应为参数对象或参数数组')
          return
        }
        closeDialog(formData.value.type, result)
      } catch (e) {
        ElMessage.error('JSON格式错误')
      }
    }
  })
}
	
	const emits = defineEmits(['closeDialog'])
	const closeDialog=(type:string,data:any)=>{
		dialog.value.visible=false;
		dialog.value.title="";
		emits('closeDialog',type,data)
		resetForm();
	}
	
	/**
	 * 重置表单
	 */
	function resetForm() {
		formRef.value.resetFields();
		formRef.value.clearValidate();
		formData.value.id = undefined;
		formData.value.type = undefined;
		formData.value.content = undefined;
	}	
	defineExpose({
	  openDialog,closeDialog
	});
	
	onMounted(() => {
	});
</script>

<style scoped>
	.custom-dialog{
		background-color: rebeccapurple;
	}
	
	:deep(.avatar-uploader .el-upload) {
	  border: 1px dashed #ccc;
	  border-radius: 6px;
	  cursor: pointer;
	  position: relative;
	  overflow: hidden;
	  width: 16rem;
	  height: 10rem;
	  
	}

	.avatar-uploader .el-upload:hover {
	  border-color: var(--el-color-primary);
	}
	
	.el-icon.avatar-uploader-icon {
	  font-size: 28px;
	  color: #8c939d;
	  width: 178px;
	  height: 178px;
	  text-align: center;
	}
	
	.thumbnail{
		height: 160px !important;
		width: 256px !important;
		-o-object-fit: fill;
		object-fit: fill;
	}
	
	.form-row{
		width: 100%;
		display: flex;
		flex-direction: row;
		padding-right: 0.625rem;;
	}
</style>